<template>
  <div style="position: absolute;top: 0%; left: 0%; width: 100%; background: whitesmoke;" v-loading="loading" class="exa_body">
    <!-- <el-card style="max-width: 99%;height: 80px;"></el-card> -->
    <div style="height: 80px; width: 100%; background: rgb(205 211 216); box-shadow: var(--el-box-shadow-light); border-radius: var(--el-border-radius-base);">
      <!-- <el-avatar :size="40" :src="ztlog" style="margin-left: 1%; margin-top: 0.9%; float: left;"/> -->
      <el-image style="width: 55px; height: 45px; margin-left: 1%; margin-top: 0.9%; float: left;" :src="ztlog" :fit="fit"/>
      <div id="countdown" style="position: relative; top:30%;">
        <el-text class="mx-1" type="primary" size="large" tag="b" style="font-size: 25px; margin-left: 1%; color:black;">云计算在线考试系统</el-text>
        <el-tag  tag="b" size="large" style="margin-left: 2%; font-size: 14px; color: black;" >
         距离考试结束还有：{{ timeAfter }}</el-tag>
         <el-tag tag="b" size="large" style="font-size: 14px; margin-left: 1%; color: black;">
         学生姓名：{{ userInfo.nickname }}</el-tag>
        </div>  
    </div>
   <div style="margin-left: 16%; margin-top: 1%;">
    
  <div ref="containerRef" style="width: 60%; height: 85vh;display: inline-block;overflow-y: auto;-ms-overflow-style: none;scrollbar-width: none; box-shadow: var(--el-box-shadow-light); border-radius: var(--el-border-radius-base);">
        <span id="part0"></span>
        <el-card :id="'part'+(index+1)" v-for="(item,index) in examination_info" :body-style="{padding:item.typeId==3||item.typeId==4?'0px':'20px'}" style="margin-bottom: 15px;">
            <template #header>
            <div class="card-header">
                <div style="display: inline-block;" class="text-ellipsis">{{index+1+". "+ item.question.split("/")[0]}}</div>
                <span style="position: relative;right: 0px;">&nbsp;&nbsp;&nbsp;{{ "( "+(item.typeId==1?'单选题':item.typeId==2?'多选题':item.typeId==3?'判断题':item.typeId==4?'简答题':null)+" )" }}</span>
            </div>
            </template>
            <el-radio-group v-if="item.typeId==1" v-model="item.stuAnswer" style="width: 10px;">
            <el-radio v-for="(text,i) in item.question.split('/')[1].split('_')" :value="i+1" size="large" @click="">{{ text }}</el-radio>
            </el-radio-group>

            <el-checkbox-group v-if="item.typeId==2" v-model="item.stuAnswer" style="width: 10px;">
                <el-checkbox v-for="(city,ii) in item.question.split('/')[1].split('_')" :value="ii+1">{{ city }}</el-checkbox>
            </el-checkbox-group>
            <!-- 判断题 -->
            <el-radio-group v-if="item.typeId==3" style="margin-left: 30px;width: 10px;" v-model="item.stuAnswer">
            <el-radio value="正确" size="large">正确</el-radio>
            <el-radio value="错误" size="large">错误</el-radio>
            </el-radio-group>
            <!-- 简答题 -->
            <!-- <template v-if="answerTxtFlog" #footer>答案：<span :style="{color:item.typeId==3 && item.answerTxt?'green':'red'}">{{ item.answerTxt }}</span></template> -->
            <el-form-item v-if="item.typeId == 4">
            <el-input v-model="item.stuAnswer" style="width: 98%" :autosize="{ minRows: 6, maxRows: 6 }" type="textarea" placeholder="请输入......"/>
          </el-form-item>
          </el-card>
    </div>
   <!-- 摄像头 -->
    <!-- <span style="margin-left: 10px; height:20%; width: 17.5%; box-shadow: var(--el-box-shadow-light); border-radius: var(--el-border-radius-base);position: absolute; border: 0px solid #73767a;">
      <video style="width: 250px;height: 250px;border-radius: 100%;margin: 20px auto; position: relative; left: 6%; top: -28%;" ref="videoElement" autoplay playsinline></video>
    </span> -->
    <div style="width: 20%;display: inline-block; overflow-y: auto;-ms-overflow-style: none;scrollbar-width: none; position: absolute;top: 31.6%;">
        <el-anchor
          style="height: 520px;padding-top: 40px;width: 300px;margin-left: 10px; border: 0px solid #73767a;border-radius: 10px;border-top: none;box-shadow: var(--el-box-shadow-light);"
          :container="containerRef"
          direction="vertical"
          type="horizontal"
          :offset="70"
          @click="handleClick"
        >
        <div style="text-align: center;margin-bottom: 50px;"><el-text class="mx-1" type="danger" size="large" tag="b" style="font-size: 20px;">{{ examina_info.name }}</el-text></div>
          <el-anchor-link v-for="(item,index) in examination_info" :style="{backgroundColor:item.stuAnswer.length==0?color:'rgb(231, 250, 240)'}" style="font-weight: 500;size: 20px;width: 35px;display: inline-block;text-align: center;border-radius: 5px;height: 35px;line-height: 55px;margin-left: 8px;" :href="'#part'+(index)">
           {{index+1}}
          </el-anchor-link>
          <el-check-tag @click="back_submit" checked style="position: absolute; left: 36%; top: 77%" type="primary">提交试卷</el-check-tag>
        </el-anchor>
        
    </div>
  </div>
</div>
<!-- 准问学生是否继续考试 -->
<el-dialog
    v-model="centerDialogVisible"
    title="温馨提示"
    width="500"
    :show-close="false"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    align-center>
    <span>请您遵守考试纪律哦</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="enterFullscreen">继续答题</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 公布结果 -->
  <el-dialog
    v-model="centerDialogVisible_result"
    title="考试结果"
    width="500"
    :show-close="false"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    align-center>
    <template #header>
      <div class="card-header">
        <span>考试名称：{{examina_info.name}}</span>
      </div>
    </template>
    <span>本次考试成绩为：{{stu_score}}分</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="query_back">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 确认用户在全屏下做答 -->
  <el-dialog
    v-model="centerDialogVisible_allult"
    title="温馨提示"
    width="500"
    :show-close="false"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    align-center>
    <span>请确保在全屏下做答</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="query_allback">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { onMounted, ref,reactive,onUnmounted } from 'vue';
import { useflagStore } from "@/store/flagStore";
import { useRouter } from 'vue-router';
import { useExaminationStore1 } from "@/store/examinationStore";
import { autoMarking } from '@/api/user/examination/examination_api';
import { useUserStore1 } from '@/store/userStore.js';
import { ElMessage,ElMessageBox } from 'element-plus';
import { useExamina_Store1 } from "@/store/examina_Store";
import ztlog from '../../assets/zt_log.jpg'

const loading =ref(false)//页面全局加载
const color = ref("rgb(245, 245, 245)")

const userInfo = useUserStore1().userInfo;//取出用户信息
const examina_info = useExamina_Store1().examina_info;//取出考试信息
const examination_info = useExaminationStore1().examinationinfo//取出考题
//将学生要添加的容器转换为数组
examination_info.forEach(element => {
       element.stuAnswer=[]
});
setTimeout(()=>{
  
},100)
const router = useRouter()
const centerDialogVisible = ref(false)  //继续考试弹框
const centerDialogVisible_result = ref(false)//公布结果
const centerDialogVisible_allult = ref(false)  //确保在全屏下做答
const videoElement = ref(null);       
const stream = ref(null);  
const timeAfter = ref()
let cutNumber = 0;   //作弊次数
centerDialogVisible_allult.value=true
// loading.value=true
// const startCamera = async () => {
//   try { 
//     // 请求访问用户的视频设备  
//     const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });  
//     videoElement.value.srcObject = mediaStream;  
//     stream.value = mediaStream;
//     loading.value = false //允许使用摄像头
//     // document.exitFullscreen();
//     if(loading.value == false){cutNumber = 0; centerDialogVisible_allult.value=true}
//     // enterFullscreen()
//   } catch (error) {  
//     cutNumber=-10 //------------------------------------------------------暂时改动-----------------------
//     // console.error('访问摄像头失败:', error);
//     //不让访问摄像头回到考试页面
//     useflagStore().clearStudentInfo()//将pinio中flag值改为true显示菜单和面包屑
//     toggleFullscreen()
//     setTimeout(()=>{
//     router.push({ path: '/user/optionExamination', query: { falg: false} });
//     },500)
//   }  
// };  

/**确保在全屏下做答 */
function query_allback(){
  centerDialogVisible_allult.value=false
  enterFullscreen()
}

const stopCamera = () => {  
  if (stream.value) {  
    // 停止视频流  
    stream.value.getTracks().forEach(track => track.stop());  
    videoElement.value.srcObject = null;  
    stream.value = null;  
  }  
}; 
/**开启全屏API方法 */
function enterFullscreen() {
       centerDialogVisible.value=false
      if (document.fullscreenElement){  
        document.exitFullscreen(); 
      } else {  
        document.documentElement.requestFullscreen();  
      }  
 } 
 
 /**关闭全屏API方法 */
 function toggleFullscreen() { 
  if (!document.fullscreenElement) { 
        enterFullscreen();
      } else {
        document.exitFullscreen();  
      }  
  }

//监测用户是否切屏
 onMounted(() => {
  //开启视像头
  document.addEventListener('visibilitychange',function(e){
            let state = document.visibilityState
            if(state == 'hidden'){
                console.log(document.visibilityState,'用户离开了');
            }
            if(state == 'visible'){
                console.log(document.visibilityState,'回来了');
            }
        }); 
        window.onblur = function (){titlefun(++cutNumber);}
        window.onfocus = function(){}
});  

/**学生成绩 */
const stu_score = ref(0)
/**提交试卷方法 */
function back_submit(){
  //查询是否右未答完题
  var boo=true
  examination_info.forEach(element => {
        if (element.stuAnswer.length==0) {
            boo=false
        }
    });
    if (boo) {
             cutNumber=-10   //------------------------------------------------------暂时改动-----------------------
            loading.value=true
            caseABCDStr()//转换成ABCD形式用于提交后端
            autoMarking(examination_info).then(res=>{
            loading.value=false
               if(res.data.code == 200){
                   centerDialogVisible_result.value = true
                   stu_score.value=res.data.obj  //学生考试分数
                   loading.value=false
                   ElMessage.success(res.data.message)
               }else{
                   ElMessage.error("提交失败")
               }
            })
            // back_ExaminationInfo() //退出到考试信息页面
           
    }else{
        ElMessageBox.confirm(
            '还有试题未答是否交卷?',
            '提交试卷',
            {
            cancelButtonText: '取消',
            confirmButtonText: '提交',
            type: 'warning',
            }
        )
            .then(() => {
            ElMessage({
                type: 'success',
                message: '交卷成功请稍后...',
            })
            cutNumber=-10   //------------------------------------------------------暂时改动-----------------------
            loading.value=true
            caseABCDStr()//转换成ABCD形式用于提交后端
            autoMarking(examination_info).then(res=>{
               if(res.data.code == 200){
                   centerDialogVisible_result.value = true
                   stu_score.value=res.data.obj  //学生考试分数
                   loading.value=false
                   ElMessage.success(res.data.message)
               }else{
                   ElMessage.error("提交失败")
               }
            })
            // back_ExaminationInfo() //退出到考试信息页面
           
            })
            .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消提交',
            })
              color.value="rgb(254, 122, 122)"
            })
        }
  
  //转换成数组用于回显ABCD
   setTimeout(()=>{
    casenumber()
   },800)
}

/*转换成ABCD形式用于提交后端*/
function caseABCDStr(){
  examination_info.forEach(element => {
       element.subId=null
       element.answerTxt=null
       element.state=null
          //赋值试卷id
          // element.examId=localStorage.getItem("examId")
          element.examId=examina_info.id
          //赋值用户id
          element.userId=userInfo.userId
      
        if(element.typeId == 2){//多选
            if(element.stuAnswer.length>0){
              let duoxuan = '';
            element.stuAnswer.forEach(element => {
                if(element == 1){
                  duoxuan += 'A'
                }
                if(element == 2){
                   duoxuan += 'B'
                }
                if(element == 3){
                   duoxuan += 'C'
                }
                if(element == 4){
                    duoxuan += 'D'
                }
            });
              element.stuAnswer=duoxuan
            }else{
              element.stuAnswer=''  //这是填写的多选题改为字符串
            }
          }
      if(element.typeId == 1){//单选
          if(element.stuAnswer != null){  
             if(element.stuAnswer == 1){
              element.stuAnswer = 'A'
             }else if(element.stuAnswer == 2){
               element.stuAnswer = 'B'
             }else if(element.stuAnswer == 3){
                element.stuAnswer = 'C'
             }else if(element.stuAnswer == 4){
                element.stuAnswer = 'D'
             }
          }
          if(element.stuAnswer.length == 0){
            element.stuAnswer=''
          }
       }

     if(element.typeId == 3){  //判断题
        if(element.stuAnswer.length == 0){
          element.stuAnswer=''
        }
     }

     if(element.typeId == 4){  //简答题
        if(element.stuAnswer.length == 0){
          element.stuAnswer=''
        }
     }
   });
}
/*转换成数组形式用于回显*/
function casenumber(){
  examination_info.forEach(element => {
    if(element.typeId == 2){//多选
            if(element.stuAnswer.length>0){
                let duoxuan = [];
             let arr=element.stuAnswer.split("")
             arr.forEach(element => {
            
                if(element == 'A'){
                    duoxuan.push(1)
                }
                if(element == 'B'){
                    duoxuan.push(2)
                }
                if(element == 'C'){
                    duoxuan.push(3)
                }
                if(element == 'D'){
                    duoxuan.push(4)
                }
            });
              element.stuAnswer=duoxuan
            }else{
              element.stuAnswer=[]  //这是填写的多选题改为字符串
            }
          }

       if(element.typeId == 1){//单选
      if(element.stuAnswer != null){  
         if(element.stuAnswer == 'A'){
          element.stuAnswer = 1
         }else if(element.stuAnswer == 'B'){
           element.stuAnswer = 2
         }else if(element.stuAnswer == 'C'){
            element.stuAnswer = 3
         }else if(element.stuAnswer == 'D'){
            element.stuAnswer = 4
         }
        }
        if(element.stuAnswer.length == 0){
          element.stuAnswer=[]
        }
       }

       if(element.typeId == 3){  //判断题
        if(element.stuAnswer.length == 0){
          element.stuAnswer=[]
        }
     }

     if(element.typeId == 4){  //简答题
        if(element.stuAnswer.length == 0){
          element.stuAnswer=[]
        }
     }
   });
}

const isFullscreen = ref(false);
 /**监听学生是否退出全屏状态 */
document.addEventListener('fullscreenchange', () => {
   isFullscreen.value = !!document.fullscreenElement;
   //false代表用户退出全屏状态
   if(!!document.fullscreenElement == false){
          //  ++cutNumber
       titlefun(++cutNumber)
      //  centerDialogVisible.value=true
      if(cutNumber == 1){
              centerDialogVisible.value=true
              //"您还剩2次机会"
          }else if(cutNumber ==2){
              centerDialogVisible.value=true
              //您还剩1次机会
          }else if(cutNumber ==3){
                //没次机会
                cutNumber=-10
          }
   }
});

/*监听用户鼠标右键*/
document.addEventListener('contextmenu', function(event) {// 获取整个文档对象
  // 阻止默认行为，即阻止右键菜单的显示
  event.preventDefault();
  // 可选：在这里可以添加其他逻辑，比如显示一个自定义的右键菜单
}, false);

document.addEventListener('keydown', function(e) {  
  if(e.keyCode === 123) { // F12的keyCode是123  
    e.preventDefault();  
    e.returnValue = false;  
    return false;  
  }  
  // 也可以尝试阻止Ctrl+Shift+I等快捷键  
  if(e.ctrlKey && e.shiftKey && (e.keyCode === 'I'.charCodeAt(0) || e.keyCode === 'J'.charCodeAt(0) || e.keyCode === 'C'.charCodeAt(0))) {  
    e.preventDefault();  
    e.returnValue = false;  
    return false;  
  }  
  // 如果需要阻止更多快捷键，可以继续添加  
}, true); // 第三个参数为true表示在捕获阶段处理事件

  /*判断用户次数  如果3次都用完了  强制胶卷并且0分*/
    function titlefun(cutNumber){
      if(cutNumber == 1){
            ElMessage.warning("您还有2次机会哦!!!")
          }else if(cutNumber ==2){
            ElMessage.warning("您还有1次机会哦!!!")
          }else if(cutNumber ==3){
                cutNumber=-10   //------------------------------------------------------暂时改动-----------------------
              ElMessage.error("您没有机会了哦~")
              loading.value=true
              forcepaper()//强制交卷清空数据
              autoMarking(examination_info).then(res=>{
              loading.value=false
               if(res.data.code == 200){
                   centerDialogVisible_result.value = true
                   stu_score.value=0  //学生考试分数
                   loading.value=false
                   ElMessage.success(res.data.message)
               }else{
                   ElMessage.error("提交失败")
               }
            })
            // back_ExaminationInfo()
          }
    }

//强制交卷清空数据       
function forcepaper(){
   //强制交卷    清空数据   保留学生id  和试卷id
   examination_info.forEach(element => {
        element.subId=null
        element.answerTxt=""
        element.state=null
       //赋值试卷id
      //  element.examId=localStorage.getItem("examId")
       element.examId=examina_info.id
       //赋值用户id
       element.userId=userInfo.userId
       if(element.typeId == 1){   //单选
          element.stuAnswer=''
       }
       if(element.typeId == 2){  //多选
          element.stuAnswer=''
       }
       if(element.typeId == 3){  //判断
          element.stuAnswer=''
       }
       if(element.typeId == 4){   //简答
          element.stuAnswer=''
       }
    });
}

//封装的方法
function countdown() {
  loading.value=true
 // 设置倒计时的结束时间为未来某个时间
 var endTime = new Date(examina_info.endTime);
 // 每秒执行一次
 setInterval(function() {
     // 获取当前时间和结束时间的时间差
     var nowTime = new Date();
     var timeDiff = endTime.getTime() - nowTime.getTime();
     // 计算剩余时间
     var hours = Math.floor((timeDiff / 1000 / 60 / 60) % 24);
     var minutes = Math.floor((timeDiff / 1000 / 60) % 60);
     var seconds = Math.floor((timeDiff / 1000) % 60);
     if( hours==0 && minutes==0 && seconds==0 ){  //时间到了强制交卷
       ElMessage.success("考试时间已到啦！！！")
       loading.value=true
       caseABCDStr()//转换成ABCD形式用于提交后端
       autoMarking(examination_info).then(res=>{
         loading.value=false
         if(res.data.code == 200){
          centerDialogVisible_result.value = true
          stu_score.value=res.data.obj  //学生考试分数
          loading.value=false
           ElMessage.success(res.data.message)
         }else{
           ElMessage.error("提交失败")
         }
       })
      //  back_ExaminationInfo() //退出到考试信息页面
      }
     // 将剩余时间显示在页面上
    timeAfter.value=""+hours + " 小时" + minutes + " 分" + seconds + " 秒";
    loading.value=false
 }, 1000);
}

/**退出到考试信息页面 */
function query_back(){
  centerDialogVisible_result.value=false
  //退出到考试信息页面
  stopCamera();
  useflagStore().clearStudentInfo()//将pinio中flag值改为true显示菜单和面包屑
  document.exitFullscreen();
  router.push("/user/optionExamination")
}

/*暂时退出方法*/
function back_ExaminationInfo(){
  stopCamera();
  useflagStore().clearStudentInfo()//将pinio中flag值改为true显示菜单和面包屑
  toggleFullscreen()
  router.push("/user/optionExamination")
}

countdown()
onUnmounted(() => {  
  // 组件卸载时停止摄像头  
  if (stream.value) {  
    stopCamera();  
  }  
  // 切屏组件删除
  document.removeEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement;
  });
});  
</script>
<style>
.btn_href:hover{
  background-color:rgba(255, 255, 255, 0.5); 
  /* opacity: 0.5; */
}
.exa_body{
 /* width:130px; height:20px; */
 background:url(images/servicesbg.gif) 0 0 repeat-x whitesmoke; 
 font: 16px/12px;
}

html,body{
  margin: 0;  
  padding: 0;  
  height: 100%;  
  background: whitesmoke;
  overflow: hidden; /* 防止内部元素产生滚动条 */ 
 /* margin:34px 0 0 37px; */
}

.text-ellipsis{
    width: 89%;
}
</style>